# global helper methods are accessible in all controllers and views
module GlobalHelper
  include PagerHelper
  def current_user
    login_by_token unless logged_in?
    @current_user ||= session[:user_id] ? User.find_by_id(session[:user_id]) : Guest.new
  end
  
  def current_user=(user)
    session[:user_id] = user.id if @current_user = user
  end
    
  def login_by_token
    self.current_user = User.find_by_id_and_login_token(*cookies[:rorbb_remember_me].split(':')) if cookies[:rorbb_remember_me]
  end

  def logged_in?
    !session[:user_id].nil?
  end
  
  def is_admin?
    current_user.is_a? Admin
  end

  def topic_post_path(post)
    post = Post.find(post) unless post.kind_of? Post
    topic_path(:id => post.topic_id, :page => page_with_position(post.position, posts_per_page), :anchor => "post#{post.id}")
  end
  
  def topic_pages(topic)
    pager = Pager.new(posts_per_page, topic.posts.size)
    if pager.last_page > 1
      pages = if pager.last_page > 5
        [1,2,3, '..', pager.last_page]
      else
        (1..pager.last_page)
      end
      
      pages.inject('pages: ') do |out, page|
        out + link_to_unless(page == '..', page, topic_path( :id => topic.id, :page => page), :class => 'number_page') + "\n"
      end
    end
  end
  
  def page_with_position(position, per_page)
    (position.to_f / per_page.to_f).ceil
  end
  
  # later we might make these dynamic based on user input
  def posts_per_page
    10
  end
  
  def topics_per_page
    10
  end
end
